package org.wat.wcy.isi.mmazur.bp.io.model;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import org.wat.wcy.isi.mmazur.bp.io.BinaryObject;
import org.wat.wcy.isi.mmazur.bp.io.model.enums.ConditionType;

public class TransitionCondition extends BinaryObject {

	private final static int CONDITION_SIZE = 512;

	private ConditionType type;
	private String expression;
	
	public TransitionCondition() {
		type = ConditionType.NULL;
		expression = "";
	}

	public TransitionCondition(ConditionType type) {
		this.type = type;
		this.expression = "";
	}
	
	public TransitionCondition(ConditionType type, final String expression) {
		this.type = type;
		this.expression = expression;
		if (this.expression == null) {
			this.expression = "";
		}
	}
	
	public ConditionType getType() {
		return type;
	}

	public void setType(ConditionType type) {
		this.type = type;
	}

	public String getExpression() {
		return expression;
	}

	public void setExpression(String expression) {
		this.expression = expression;
	}

	@Override
	public void write(RandomAccessFile raf) {
		try {
			String str = expression != null ? expression : "";
			byte b[] = Arrays.copyOf(str.getBytes(), CONDITION_SIZE);
			raf.write(b);
			raf.writeInt(type.ordinal());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void read(RandomAccessFile raf) {
		try {
			byte b[] = new byte[CONDITION_SIZE];
			raf.read(b, 0, CONDITION_SIZE);
			expression = new String(b).trim();
			int ord = raf.readInt();
			type = ConditionType.values()[ord];
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static int sizeOf() {
		return CONDITION_SIZE + (int)(Integer.SIZE / 8);
	}
}
